package com.cloud.pole.tool.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.exception.ParamException;
import com.cloud.pole.common.util.DateUtils;
import com.cloud.pole.common.util.RegexUtils;
import com.cloud.pole.common.util.UUIDUtils;
import com.cloud.pole.tool.config.FileUploadConfiguration;
import com.cloud.pole.tool.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;

/*
*2019年6月25日
*cloud-tool
*author:frank-chen
*/
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
	@Autowired
	FileUploadConfiguration fileUploadConfiguration;
	
	@Override
	public String uploadImage(byte[] btImage, String useType, String fileType) throws Exception {
		// TODO Auto-generated method stub
		Date date = new Date();  
		String strDate = DateUtils.formatDate(date, "yyMMdd");
		String ext = "." + fileType;
		String newFileName =  UUIDUtils.generateShortUuid15() + date.getTime() + ext;
		if(!RegexUtils.isImageFile(newFileName)){
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "文件类型错误");
		}		
		String filePath = fileUploadConfiguration.getUploadImagePath();
		filePath = filePath + java.io.File.separator + useType;
		String newFilePath = filePath + java.io.File.separator + newFileName;   
		createNotExistsDir(filePath);
		String returnFileUrl = "/" + useType + "/" + newFileName; 
		
	    BufferedOutputStream bufferedOutputStream = null;
	    FileOutputStream fileOutputStream = null;
	    try {
	    	fileOutputStream = new FileOutputStream(new File(newFilePath));
	  	    bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
	  	    bufferedOutputStream.write(btImage);
		 }
	    catch (Exception e)
	    {
	        e.printStackTrace();
	    }
	    finally
	    {
	    	if (bufferedOutputStream != null){
	    		bufferedOutputStream.close();
            }
            if (fileOutputStream != null){
            	fileOutputStream.close();
            }
	    }
		return returnFileUrl;
	}

	 /**
	  * 先判断目录是否存在，如果不存在，则先建立目录
    *
    * @param path
    * @return
    */
   public static boolean createNotExistsDir(String path) {
       if (path == null || path.length() < 1) {
           return false;
       }
       java.io.File myfile = new java.io.File(path);
       if (myfile.exists() == false) {
           return myfile.mkdirs();
       }
       return true;
   }
}
